package org.csu.sei.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.sei.common.BaseConstant;
import org.csu.sei.common.PageRes;
import org.csu.sei.entity.News;
import org.csu.sei.entity.User;
import org.csu.sei.persistence.UserMapper;
import org.csu.sei.service.IUserService;
import org.csu.sei.util.MD5Util;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import static org.csu.sei.common.BaseConstant.Role.WAITINGPASS;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, BaseConstant {
    @Resource
    private UserMapper userMapper;

    @Override
    public Long getIdFromName(String username){
        return selectUserByUsername(username).getId();
    }

    @Override
    public User insertUser(User user) {
        if(user.getPassword() == null || user.getUsername() == null){
            throw new RuntimeException();
        }
        user.setId(null);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);
        User checkuser = user;//mbp插入对象后会改变原对象为插入后的对象
        return checkuser;
    }

    @Override
    public User selectUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public int updateUserInfo(User user){
        //检索数据库内的对象，对传回的username或userID进行判断
        User usercheck = userMapper.selectById(user.getId());
        if (usercheck == null){
            usercheck = selectUserByUsername(user.getUsername());
        }
        //不变化的量
        user.setUpdateTime(LocalDateTime.now());
        user.setRole(usercheck.getRole());
        user.setCreateTime(usercheck.getCreateTime());
        user.setId(usercheck.getId());
        return userMapper.updateById(user);
    }

    @Override
    public User selectUserById(Long id){
        return userMapper.selectById(id);
    }

    @Override
    public String selectAnswerFromUserId(Long id){
        String answer;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        answer = userMapper.selectOne(queryWrapper).getAnswer();
        return answer;
    }

    @Override
    public int updateUserRole(Long userid, int role) {
        User user = userMapper.selectById(userid);
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        user.setRole(role);
        return userMapper.updateById(user);
    }

    @Override
    public List<User> selectUserUnReg() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role",WAITINGPASS.getCode()).select(User.class, info -> !info.getColumn().equals("password"));
        queryWrapper.orderBy(true,false,"create_time");
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList;
    }

    @Override
    public List<User> selectAllUser() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(User.class, info -> !info.getColumn().equals("password"));
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList;
    }

    @Override
    public  List<User> addSome(List<String> addList, int role){
        List<User> resList = new ArrayList<>();
        for(String username : addList){
            User user = new User();
            user.setRole(role);
            user.setUsername(username);
            user.setPassword(MD5Util.formPassToDBPass("123456"));
            User resUser = insertUser(user);
            resUser.setPassword(null);
            resList.add(resUser);
            //错误输出日志
        }
        return resList;
    }

    @Override
    public int deleteSome(List<Long> idList) {
        int count = 0;
        for (Long id : idList){
            count = count + deletUserById(id);
        }
        return count;
    }

    @Override
    public int setSomeRole(List<Long> idList, int status) {
        for(Long id : idList){
            User user = userMapper.selectById(id);
            user.setRole(status);
            userMapper.updateById(user);
        }
        return 1;
    }

    @Override
    public int deletUserById(Long userid) {
        int result = userMapper.deleteById(userid);
        return result;
    }

    @Override
    public PageRes queryUserListBySomeCondition(int page, int limit,String username, List<Integer>roles){
        IPage<User> userIPage = new Page<>(page,limit);
        QueryWrapper<User> queryWrapper= new QueryWrapper<>();
        if(username != null && !username.equals("")){
            int userid;
            try {
                userid= Integer.valueOf(username);
                queryWrapper.like("id",userid);
            }catch (Exception e){
                log.warn(username + "is string");
            }
            queryWrapper.like("username",username);
        }
        if(roles!=null && !roles.isEmpty())
        {
            queryWrapper.and(queryWrapper1 -> {
                for (int role : roles) {
                    queryWrapper1.eq("role", role).or();
                }
            });
        }
        else{
            queryWrapper.and(queryWrapper1 -> queryWrapper1.ne("role",100));
        }
        if ((roles.isEmpty() || roles == null)&& username == null){
            queryWrapper.ne("id",-1);
        }
        int count = userMapper.selectCount(queryWrapper);
        queryWrapper.and(queryWrapper1 -> queryWrapper1.ne("role",0));
        queryWrapper.select("id","username","email","phone","question","answer","role","create_time","update_time");
        queryWrapper.orderBy(true,false,"create_time");
        userIPage = userMapper.selectPage(userIPage,queryWrapper);
        return new PageRes(page+1 , limit, count, (int)count /limit+1 , userIPage.getRecords());
    }

    @Override
    public int changByAdmin(User user) {
        User usercheck = userMapper.selectById(user.getId());
        if(user.getPassword() == null || user.getPassword().isEmpty() || user.getPassword().length() < 6){
            user.setPassword(usercheck.getPassword());
        }
        user.setRole(usercheck.getRole());

        user.setUpdateTime(LocalDateTime.now());
        user.setRole(usercheck.getRole());
        user.setCreateTime(usercheck.getCreateTime());
        user.setId(usercheck.getId());

        return userMapper.updateById(user);
    }

    @Override
    public String selectQuestion(long id){
        String question;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        User user = userMapper.selectOne(queryWrapper);
        question = user.getQuestion();
        return question;
    }

}
